package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.ForumMapper;
import com.example.mapper.ForumTopicMapper;
import com.example.pojo.ForumTopic;
import com.example.pojo.PageBean;
import com.example.service.ForumTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-08-20
 */
@Service
public class ForumTopicServiceImpl extends ServiceImpl<ForumTopicMapper, ForumTopic> implements ForumTopicService {
    @Autowired
    private ForumTopicMapper forumTopicMapper;
    @Autowired
    private ForumMapper forumMapper;

    @Override
    public List<ForumTopic> getForumTopicsByFid(Integer fid) {
        return forumTopicMapper.selectByFId(fid);
    }

    @Override
    public List<ForumTopic> getForumTopics(Integer tid) {
        return forumTopicMapper.getForumTopics(tid);
    }

    @Override
    public PageBean<ForumTopic> getByPage(Integer currentPage, Integer pageSize, Integer fid) {
        currentPage = (currentPage - 1) * pageSize;
        //查询数据
        List<ForumTopic> topicList = forumTopicMapper.getByPage(currentPage, pageSize, fid);

        //查询总数
        LambdaQueryWrapper<ForumTopic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(fid != null, ForumTopic::getForumId, fid);

        return new PageBean<>(currentPage,pageSize,count(wrapper),topicList);
    }

    /**
     * 添加主题
     * @param forumTopic 主题对象
     * @param forumId 主题所属论坛
     * @param topicCount 论坛主题数量
     * @param articleCount 主题数+回复数
     */
    @Override
    public boolean saveTopic(ForumTopic forumTopic, Integer forumId, Integer topicCount, Integer articleCount) {
        //保存主题对象，并获取主题id
        boolean save = this.save(forumTopic);
        Integer lastTopicId = forumTopic.getTid();//最后添加的主题id

        //修改论坛对象
        topicCount++;
        articleCount++;
        boolean updateForum = forumMapper.updateForum(forumId, topicCount, articleCount, lastTopicId);
        return save && updateForum;
    }

}
